import poser, os, sys, string, re

os.chdir( os.path.dirname(poser.AppLocation()) )

sys.path.append( os.path.join("Runtime","Python","PoseWorks","GlowWorm","Data"))

import gwrRender, gwrPass, gwrJob
from gwrVars import *

def color(rgb):
	r, g, b = rgb
	return gwrPass.color( float(r), float(g), float(b) )

def aoOpts(aoLines):
	ao = gwrPass.occlusionOptions()
	for k, v in aoLines:
		setattr(ao, k, float(v))
	return ao

def dict2Pzr(kvs, indent=1):
	tab = "\t" * indent
	s = "\n%s{" % tab 
	for k,v in kvs.items():
                if repr(v) == "True":
                        v = 1
                elif repr(v) == "False":
                        v = 0
		if type(v) == dict:
			s = s + "\n%s%s" % (tab, k)
			s = s + dict2Pzr(v, indent=indent+1)
		else:
			s = s + "\n%s%s %s" % (tab, k, v)
	s = s + "\n%s}" % tab
	return s

def rsHeader():
	return "{\nversion\n\t{\n\tnumber 6\n\t}\n"

def rsFooter():
	return "\n}"

def printableSettings(rs):
	s = rsHeader()

def writeRenderPass(renderPass, indent=0):
	d = renderPass.get()
	s = "\n\n%srenderPass %s" % ("\t"*indent, d["id"])
	s = s + dict2Pzr(d, indent=indent+1)
	return s

def writeRenderSettings(renderSettings):
	s = "\n\nrenderSettings\n\t{"
	if hasattr(renderSettings,"camera"):
		s = s + "\n\tcamera %s" % renderSettings.camera
	else:
		s = s + "\n\tcamera USEDOC"
	s = s + "\n\tengine %i" % renderSettings.engine.engineCode() + dict2Pzr(renderSettings.engine.options, indent=2)
	s = s + "\n\tdoc" + dict2Pzr(renderSettings.doc.options, indent=2)
	s = s + "\n\tmovie" + dict2Pzr(renderSettings.movie.options, indent=2)
	s = s + "\n\tgeneral" + dict2Pzr(renderSettings.general.options, indent=2)
	return s + "\n\t}"

def writeJob(renderJob):
	s = rsHeader()
	s = s + "\njob\n\t{"
	s = s + "\n\tsrcpath %s" % renderJob.srcpath
	s = s + "\n\toutdir %s" % renderJob.outdir
	s = s + "\n\twidth %s" % renderJob.width
	s = s + "\n\theight %s" % renderJob.height
	s = s + "\n\tformat %s" % renderJob.format
	if len(renderJob.range) == 2:
		s = s + "\n\trange %i %i" % (renderJob.range[0],renderJob.range[1])
	else:
		s = s + "\n\trange %s" % renderJob.range
	s = s + "\n\t}"
	if renderJob.settings:
		s = s + writeRenderSettings( renderJob.settings )
	for rp in renderJob.passes:
		s = s + writeRenderPass( rp )
	s = s + rsFooter()
	s = s + "\n@RAW\n" + renderJob.settings.engine.raw.strip() + "\n#RAW"
	return s

def loadRenderPass(input):
	d = {}
	sub = []
	doSub = 0
	iS = input.index("\t{")
	for line in input[iS+1:-1]:
		kv = line.strip().split()
		if kv == []:
			continue
		elif kv[0] == "{":
			doSub = 1
		elif kv[0] == "}":
			doSub = 0
			d[ sub[0][0] ] = aoOpts(sub[1:])
		elif len(kv) == 1 or doSub:
			sub.append( kv )
		elif kv[0] == "koColor":
			d[kv[0]] = color(kv[1:])
		elif kv[0] == "id":
			d[kv[0]] = kv[1]
		elif kv[0] == "fx6":
			d[kv[0]] = string.join(kv[1:])
		else:
			d[kv[0]] = int(kv[1])
	rp = gwrPass.renderPass()
	#id=d["id"], passPerLight=d["passPerLight"], passPerObject=d["passPerObject"], koColor=d["koColor"], lightingOnly=d["lighting"], diffuseOnly=d["diffuseOnly"], showHair=d["Ha"], showParticles=d["Fx"], hairOnly=d["hair"], zbuffer=d["zbuffer"], particlesOnly=d["particles"], shadows=d["shadows"], diffuse=d["Kd"], specular=d["Ks"], ambient=d["Ka"], translucence=d["Ku"], reflection=d["Kr"], refraction=d["Kf"], occlusion=d["occlusion"], shadowOnly=d["shadowOnly"], aoOptions=d["aoOptions"]
	#for k,v in d.items():
	#	if has_attr(rp, k): setattr(rp, k, v)
	rp.set(d)
	return rp

def loadRenderSettings(input):
	opts = {}
	engineCode = 0
	engineOpts, doEngine = {}, 0
	docOpts, doDoc = {}, 0
	movieOpts, doMovie = {}, 0
	generalOpts, doGeneral = {}, 0
	rs = gwrRender.renderSettings(gwrRender.fireFly())
	for line in input[4:-1]:
		line = line.strip()
		kv = line.split()
		if kv == []:
			continue
		elif kv[0] == "camera":
			rs.camera = kv[1]
		elif kv[0] == "engine":
			rs.setEngine( gwrRender.engineByCode(int(kv[1])) )
			doEngine = 1
		elif kv[0] == "doc":
			doDoc = 1
		elif kv[0] == "movie":
			doMovie = 1
		elif kv[0] == "general":
			doGeneral = 1
		elif doEngine and kv[0] != "{":
			if kv[0] == "}": doEngine = 0
			else: rs.setFlag(kv[0],kv[1])
		elif doDoc and kv[0] != "{":
			if kv[0] == "}": doDoc = 0
			else: rs.docFlag(kv[0],kv[1])
		elif doMovie and kv[0] != "{":
			if kv[0] == "}": doMovie = 0
			else: rs.movieFlag(kv[0],kv[1])
		elif doGeneral and kv[0] != "{":
			if kv[0] == "}": doGeneral = 0
			else: rs.genFlag(kv[0],kv[1])
	return rs

def fetchSection(input):
	sub = []
	levelsIn = 0
	for line in input:
		sub.append(line)
		kv = line.strip().split()
		if kv == []: continue
		elif kv[0] == "{":
			levelsIn = levelsIn + 1
		elif kv[0] == "}":
			levelsIn = levelsIn - 1
		if kv[0] == "}" and levelsIn == 0:
			input = input[input.index(line)+1:]
			break
		else:
			continue
	return sub, input

def loadJob(data):
	datalines = data.splitlines()[8:]
	rS = datalines.index("@RAW")
	rawlines = datalines[rS+1:-1]
	lines = datalines[:rS-1]
	jobOpts = {}
	renderPasses = []
	sub = []
	for line in lines:
		kv = line.strip().split()
		if kv == []: continue
		elif kv[0] == "}":
			lines = lines[lines.index(line)+1:]
			break
		elif (kv[0] == "width" or kv[0] == "height") and kv[1] != "USEDOC":
			jobOpts[kv[0]] = int(kv[1])
		elif len(kv) > 2 and kv[0] == "range":
			jobOpts[kv[0]] = (int(kv[1]), int(kv[2]))
		elif len(kv) > 2 and (kv[0] == "srcpath" or kv[0] == "outdir"):
			jobOpts[kv[0]] = string.join(kv[1:])
		else:
			jobOpts[kv[0]] = kv[1]
	rsIp, lines = fetchSection(lines)
	rs = loadRenderSettings(rsIp)
	rs.engine.raw = string.join(rawlines,"\n")
	while lines:
		rpIp, lines = fetchSection(lines)
		renderPasses.append( loadRenderPass(rpIp) )
	rj = gwrJob.renderJob(srcpath=jobOpts["srcpath"], outdir=jobOpts["outdir"], format=jobOpts["format"], range=jobOpts["range"], height=jobOpts["height"], width=jobOpts["width"], settings=rs, passes=renderPasses)
	for k,v in jobOpts.items():
		setattr(rj, k, v)
	return rj

def saveJobAs(job, outfile):
	fi = open(outfile,'w')
	fi.write( writeJob(job) )
	fi.close()
	return outfile

def readJob(infile):
	fi = open(infile, 'r')
	data = fi.read()
	fi.close()
	return loadJob(data)

if __name__ == '__main__':
	rs = gwrRender.rsFireFly
	rjw = writeJob( gwrJob.renderJob(range=(0,29)) )
	rj = loadJob( rjw )
	saveJobAs( rj, "001.gw6")

pass
